package com.server.sercurity.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.server.common.constants.RedisKeyConstant;
import com.server.common.exception.BusinessException;
import com.server.common.utils.JwtTokenUtil;
import com.server.common.utils.RedisUtil;
import com.server.sercurity.vo.UserDetailsVO;
import com.server.base.vo.AdminLoginSuccessVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zgr
 * @date 2023/7/18 10:17
 * @description
 */
@Slf4j
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        log.info("token:{}", token);
        if (StrUtil.isBlankOrUndefined(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        // 解析token
        Long adminId = null;
        try {
            adminId = JwtTokenUtil.getPayload(token, "adminId");
        } catch (Exception e) {
            throw new BusinessException("token非法");
        }
        // 获取userid 从redis中获取用户信息
        String redisKey = RedisKeyConstant.SYS_ADMIN + adminId;
        Object obj = redisUtil.get(redisKey);
        AdminLoginSuccessVO adminLoginSuccessVO = (AdminLoginSuccessVO) obj;
        if (ObjectUtil.isNull(adminLoginSuccessVO)) {
            throw new BusinessException("用户未登录");
        }
        UserDetailsVO userDetailsVO = new UserDetailsVO(adminLoginSuccessVO);

        //将用户信息存入到SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetailsVO, null, userDetailsVO.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request, response);
    }
}
